package com.cskaoyan.demo5.aspect;

import com.cskaoyan.demo5.bean.CskaoyanLog;
import com.cskaoyan.demo5.mapper.CskaoyanLogMapper;
import com.cskaoyan.demo5.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description：
 * @Author：BLUEBLANK
 * @Date：2024/4/19 20:30
 */

@Component
@Aspect
public class CustomAspect {
    @Pointcut("execution(* com.cskaoyan..demo5.bean.*.*(..))")
    public void pointcut1() {}

    @Pointcut("@annotation(com.cskaoyan.demo5.anno.AnimalHelloWorld) || @target(com.cskaoyan.demo5.anno.AnimalHelloWorld)")
    public void pointcut2() {}




    @Around("pointcut2()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        Object proceed;
        try {
            System.out.println("hello");
           proceed = proceedingJoinPoint.proceed();
            System.out.println("world");
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return proceed;
    }

    @Pointcut("@annotation(com.cskaoyan.demo5.anno.AddLog)")
    public void servicePointcut() {}

    @Around("servicePointcut()")
    public Object aroundService(ProceedingJoinPoint proceedingJoinPoint){
        Object proceed = null;
        try {
            // System.out.println("开始执行切面");
             proceed = proceedingJoinPoint.proceed();
             // 添加日志
            // System.out.println("开始添加日志");
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            CskaoyanLogMapper mapper = sqlSession.getMapper(CskaoyanLogMapper.class);
            String operation = proceedingJoinPoint.getTarget().getClass().getSimpleName() + "."+ proceedingJoinPoint.getSignature().getName();
            mapper.insertSelective(new CskaoyanLog(null, operation, null, new Date(), true, null));
            sqlSession.close();
            // System.out.println("添加完成");

        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return proceed;
    }
}
